<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="courseId">
            <el-select v-model="queryParams.courseId"  placeholder="请选择班级名称" @click.native="getCourses()">
              <el-option
                v-for="item in courseOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
      </el-form-item>
      <el-form-item label="学生姓名" prop="userId" >
        <el-select v-model="queryParams.userId"  placeholder="请选择学生姓名" @click.native="getUsers" @change="selectUsers(queryParams.userId)">
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName+':'+item.nickName"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入订单描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="已用课时" prop="used">
        <el-input
          v-model="queryParams.used"
          placeholder="请输入已用课时"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="剩余课时" prop="remain">
        <el-input
          v-model="queryParams.remain"
          placeholder="请输入剩余课时"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总课时" prop="total">
        <el-input
          v-model="queryParams.total"
          placeholder="请输入总课时"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入收款金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款凭证" prop="amountReceipt">
        <el-input
          v-model="queryParams.amountReceipt"
          placeholder="请输入收款凭证"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退款凭证" prop="refundReceipt">
        <el-input
          v-model="queryParams.refundReceipt"
          placeholder="请输入退款凭证"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
                        v-model="queryParams.startTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
                        v-model="queryParams.endTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择:正常;退款" clearable>
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收款方式" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择收款方式：现金，支付宝，微信" clearable>
          <el-option
            v-for="dict in dict.type.pay_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款金额" prop="refund">
        <el-input
          v-model="queryParams.refund"
          placeholder="请输入退款金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="折扣价" prop="discountPrice">
        <el-input
          v-model="queryParams.discountPrice"
          placeholder="请输入折扣价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center" prop="course.name" />
      <el-table-column label="任课老师" align="center" prop="teacher.nickName" />
      <el-table-column label="学生" align="center" prop="student.nickName" />
      <el-table-column label="班级描述" align="center" prop="description" />
      <el-table-column label="已用课时" align="center" prop="used" />
      <el-table-column label="剩余课时" align="center" prop="remain" />
      <el-table-column label="总课时" align="center" prop="total" />
      <el-table-column label="收款金额" align="center" prop="amount" />
      <el-table-column label="收款凭证" align="center" prop="amountReceipt" >
        <template slot-scope="scope">
          <el-image :src="scope.row.amountReceipt"  v-show="(scope.row.amountReceipt)"/>
        </template>
      </el-table-column >
      <el-table-column label="退款凭证" align="center" prop="refundReceipt">
        <template slot-scope="scope" >
          <el-image :src="scope.row.refundReceipt" v-show="(scope.row.refundReceipt)"/>
        </template>
      </el-table-column>
      <!--<el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column label="更新时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="正常;退款" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="收款方式" align="center" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_type" :value="scope.row.payType"/>
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center" prop="refund" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="折扣价" align="center" prop="discountPrice" />

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
          <el-form-item label="课程名称" prop="courseId" required >
             <el-select v-model="form.courseId"  placeholder="请选择课程名称" @click.native="getCourses" @change="selectCourses(form.courseId)" width="380px">
              <el-option
                v-for="item in courseOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学生姓名" prop="userId" required >
            <el-select v-model="form.userId"  placeholder="请选择学生姓名" @click.native="getUsers" @change="selectUsers(form.userId)" width="380px">
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName+':'+item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
       <!-- <el-col :span="12">
          <el-form-item label="已用课时" prop="used">
            <el-input v-model="form.used" readonly/>
          </el-form-item>
        </el-col>-->
        <el-col>
          <el-form-item label="订单描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入订单描述" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="剩余课时" prop="remain">
            <el-input v-model="form.remain" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总课时" prop="total">
            <el-input v-model="form.total" readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="原价" prop="amount">
            <el-input v-model="form.amount" readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="折扣价" prop="discountPrice">
            <el-input v-model="form.discountPrice" readonly />
          </el-form-item>
        </el-col>


        <el-col :span="12">
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select v-model="form.orderStatus" placeholder="请选择:正常;退款">
              <el-option
                v-for="dict in dict.type.order_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收款方式" prop="payType">
            <el-select v-model="form.payType" placeholder="请选择收款方式：现金，支付宝，微信">
              <el-option
                v-for="dict in dict.type.pay_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="退款金额" prop="refund">
            <el-input v-model="form.refund" placeholder="请输入退款金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>

        <el-col>
          <el-form-item label="收款凭证" prop="amountReceipt">
            <el-upload
              :action="uploadImgUrl"
              list-type="picture-card"
              :on-success="handleUploadSuccess"
              :before-upload="handleBeforeUpload"
              :limit="limit"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              name="file"
              :on-remove="handleRemove"
              :show-file-list="true"
              :headers="headers"
              :file-list="fileList"
              :on-preview="handlePictureCardPreview"
              :class="{hide: this.fileList.length >= this.limit}"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col>
          <el-form-item label="退款凭证" prop="refundReceipt">
            <el-upload
              :action="uploadImgUrl"
              list-type="picture-card"
              :on-success="handleUploadSuccessRefund"
              :before-upload="handleBeforeUpload"
              :limit="limit"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              name="file"
              :on-remove="handleRemoveRefund"
              :show-file-list="true"
              :headers="headers"
              :file-list="fileRefundList"
              :on-preview="handlePictureCardPreview"
              :class="{hide: this.fileRefundList.length >= this.limit}"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>

  </div>
</template>

<script>
  import { listOrder, getOrder, delOrder, addOrder, updateOrder,increaseClass,decreaseClass } from "@/api/edu/order";
  import { listCourse, getCourse, delCourse, addCourse, updateCourse } from "@/api/edu/course";
  import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, listStudent } from "@/api/system/user";
  import { getToken } from "@/utils/auth";
  export default {
    name: "Decrease",
    dicts: ['pay_type', 'order_status'],
    props: {
      value: [String, Object, Array],
      // 图片数量限制
      limit: {
        type: Number,
        default: 1,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ["png", "jpg", "jpeg"],
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单管理表格数据
        orderList: [],
        // 课程选项
        courseOptions: [],
        userOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
        pageSize: 10,
        userId: null,
        courseId: null,
          description: null,
          used: null,
          remain: null,
          total: null,
          amount: null,
          amountReceipt: null,
          refundReceipt: null,
          startTime: null,
          endTime: null,
          orderStatus: null,
          payType: null,
          refund: null,
          discountPrice: null,
          used: 1,
        },
        number: 0,
        uploadList: [],
        dialogImageUrl: "",
        dialogVisible: false,
        hideUpload: false,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileList: [],
        uploadRefundList: [],
        fileRefundList: [],
        // 表单参数
        form: {},
        amountReceipt: null,
        refundReceipt: null,
        // 表单校验
        rules: {
        }
      };
    },
    created() {
      this.getList();
      listUser().then(response=>{
        this.userList = response.rows;
      });
    },
    mounted(){
       this.getCourses();
       this.getUsers()
    },

    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
    },
    methods: {
      /** 查询订单管理列表 */
      getList() {
        this.loading = true;
        listOrder(this.queryParams).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          userId: null,
          courseId: null,
          description: null,
          used: null,
          remain: null,
          total: null,
          amount: null,
          amountReceipt: null,
          refundReceipt: null,
          startTime: null,
          endTime: null,
          orderStatus: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          payType: null,
          refund: null,
          remark: null,
          discountPrice: null,
          amountReceipt: null,
          refundReceipt: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.refundReceipt = null;
        this.amountReceipt = null;
        this.title = "添加订单管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getOrder(id).then(response => {
          this.fileRefundList = [];
          this.fileList = [];
          this.form = response.data;
          this.refundReceipt = this.form.refundReceipt
          this.amountReceipt = this.form.amountReceipt
          if(this.form.amountReceipt!=null)
          {
            if ( this.form.amountReceipt.length>0)
            this.fileList.push({ name: "amount", url: this.form.amountReceipt });
          }
          if(this.form.refundReceipt!=null )
          {
            if(this.form.refundReceipt.length>0)
            this.fileRefundList.push({ name: "refund", url: this.form.refundReceipt });
          }
          this.open = true;
          this.title = "修改订单管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.amountReceipt = this.amountReceipt
            this.form.refundReceipt = this.refundReceipt
            if (this.form.id != null) {
              updateOrder(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addOrder(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 增加课时按钮操作 */
      handleIncreaseClass(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认为编号为"' + ids + '"增加课时？').then(function() {
          return increaseClass(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("增加成功");
        }).catch(() => {});
      },
      /** 上课打卡按钮操作 */
      handleDecreaseClass(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认为编号为"' + ids + '"上课打卡？').then(function() {
          return decreaseClass(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("减少成功");
        }).catch(() => {});
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除订单管理编号为"' + ids + '"的数据项？').then(function() {
          return delOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('edu/order/export', {
          ...this.queryParams
        }, `order_${new Date().getTime()}.xlsx`)
      },
      /** listCourse */
      getCourses() {
        let self = this
        console.log("1")
        listCourse().then(response=>{
          self.courseOptions = response.rows;
        });
      },
      selectCourses(courseId,row) {
        let self = this
        let course = self.courseOptions[self.courseOptions.findIndex(item=>item.id===courseId)]
        self.form.amount = course.amount;
        self.form.discountPrice = course.discountPrice;
        self.form.total = course.total;
      },
      /** listUser */
      getUsers() {
        let self = this
        console.log("2")
        listStudent().then(response=>{
          self.userOptions = response.rows;
        });
      },
      selectUsers(userId) {
        let self = this
        let user = self.userOptions[self.userOptions.findIndex(item=>item.userId===userId)]
        debugger
        self.form.userId = user.userId
        // console.log(user.userId)
      },
      // 删除图片
      handleRemove(file, fileList) {
        const findex = this.fileList.map(f => f.name).indexOf(file.name);
        if(findex > -1) {
          this.fileList.splice(findex, 1);
          this.$emit("input", this.listToString(this.fileList));
        }
        this.amountReceipt = "";
      },
      // 上传成功回调
      handleUploadSuccess(res) {
        this.uploadList.push({ name: res.fileName, url: res.url });
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList);
          this.uploadList = [];
          this.number = 0;
          this.amountReceipt = this.listToString(this.fileList);
          this.$modal.closeLoading();
        }
      },
      // 上传前loading加载
      handleBeforeUpload(file) {
        let isImg = false;
        if (this.fileType.length) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          isImg = this.fileType.some(type => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
        } else {
          isImg = file.type.indexOf("image") > -1;
        }

        if (!isImg) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
          return false;
        }
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传图片，请稍候...");
        this.number++;
      },

      //退款凭证
      // 删除图片
      handleRemoveRefund(file, fileList) {
        const findex = this.fileRefundList.map(f => f.name).indexOf(file.name);
        if(findex > -1) {
          this.fileRefundList.splice(findex, 1);
          this.$emit("input", this.listToString(this.fileRefundList));
        }
        this.refundReceipt = "";

      },
      // 上传成功回调
      handleUploadSuccessRefund(res) {
        this.uploadRefundList.push({ name: res.fileName, url: res.url });
        if (this.uploadRefundList.length === this.number) {
          this.fileRefundList = this.fileRefundList.concat(this.uploadRefundList);
          this.uploadRefundList = [];
          this.number = 0;
          this.refundReceipt = this.listToString(this.fileRefundList);
          this.$modal.closeLoading();
        }
      },
      // 上传前loading加载
      handleBeforeUpload(file) {
        let isImg = false;
        if (this.fileType.length) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          isImg = this.fileType.some(type => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
        } else {
          isImg = file.type.indexOf("image") > -1;
        }

        if (!isImg) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
          return false;
        }
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传图片，请稍候...");
        this.number++;
      },

      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      },
      // 上传失败
      handleUploadError() {
        this.$modal.msgError("上传图片失败，请重试");
        this.$modal.closeLoading();
      },
      // 预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      // 对象转成指定字符串分隔
      listToString(list, separator) {
        let strs = "";
        separator = separator || ",";
        for (let i in list) {
          console.log(list[i].url)
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
        return strs != '' ? strs.substr(0, strs.length - 1) : '';
      }
    }
  };
</script>
<style scoped lang="scss">
  // .el-upload--picture-card 控制加号部分
  ::v-deep.hide .el-upload--picture-card {
    display: none;
  }
  // 去掉动画效果
  ::v-deep .el-list-enter-active,
  ::v-deep .el-list-leave-active {
    transition: all 0s;
  }

  ::v-deep .el-list-enter, .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }
</style>
